package com.wyz.saas.module.patrol

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.sqlite.db.SupportSQLiteDatabase
import com.wyz.saas.module.patrol.bean.PatrolCheckpoint
import com.wyz.saas.module.patrol.bean.dao.PatrolCheckpointDao
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch

@Database(entities = [PatrolCheckpoint::class], version = 1, exportSchema = false)
abstract class PatrolDatabaseWapper : RoomDatabase() {

    abstract fun patrolCheckpointDao(): PatrolCheckpointDao

    companion object {
        // Singleton prevents multiple instances of database opening at the
        // same time.
        @Volatile
        private var INSTANCE: PatrolDatabaseWapper? = null

        fun getDatabase(context: Context): PatrolDatabaseWapper {
            // if the INSTANCE is not null, then return it,
            // if it is, then create the database
            return INSTANCE ?: synchronized(this) {
                val instance = Room.databaseBuilder(
                    context.applicationContext,
                    PatrolDatabaseWapper::class.java,
                    "patrol_database"
                ).also {
                    it.addCallback(DatabaseCallback(PatrolModuleApplication.INSTANCE.scope))
                }.build()
                INSTANCE = instance
                instance
            }
        }
    }

    private class DatabaseCallback(
        private val scope: CoroutineScope
    ) : RoomDatabase.Callback() {
        override fun onCreate(db: SupportSQLiteDatabase) {
            super.onCreate(db)
            INSTANCE.let { database ->
                scope.launch {
                    populateDatabase(database?.patrolCheckpointDao())
                }
            }
        }

        fun populateDatabase(patrolCheckpointDao: PatrolCheckpointDao?) {
            patrolCheckpointDao?.also { dao ->
                // Delete all content here.
                dao.deleteAll()
                // Add sample words.
                var word = PatrolCheckpoint()
                dao.insert(word)
                word = PatrolCheckpoint()
                dao.insert(word)
                // TODO: Add your own words!
                word = PatrolCheckpoint()
                dao.insert(word)
            }
        }
    }
}